#!/bin/bash

# Copyright (c) 2023 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

ROOT_DIR=`pwd`

OHOS_SDK=$ROOT_DIR/ohos-sdk/linux/native
DEPOT_TOOLS=$ROOT_DIR/depot_tools

function check_prepare () {
    if [ ! -d $OHOS_SDK ]
    then
        echo "sdk not ready ##############"
        return 1
    fi

    if [ ! -d $DEPOT_TOOLS ]
    then
        echo "[ERROR] webrtc build depends depot tools! please make sure your depot tools have been ready!"
        return 1
    fi

    export PATH=$DEPOT_TOOLS:$PATH

    return 0
}

function downlaod_thirdparty() {

    if [ -d third_party ]
    then
        return 0
    fi

    git clone https://gitee.com/zhong-luping/webrtc_third_party.git
    if [ $? -ne 0 ]
    then
        echo "git clone webrtc third_party failed!!"
        return 1
    fi

    mv webrtc_third_party/third_party ./
    rm -rf webrtc_third_party

    return 0
}

function start_build() {
    cd ohos_webrtc
    
    downlaod_thirdparty
    if [ $? -ne 0 ]
    then
        echo "[ERROR]downlaod_thirdparty failed!"
        return 1
    fi
    
    git submodule update --init --recursive            ## git clone submodules

    local arguments="target_cpu=\"arm64\" target_os=\"ohos\" \
    ohos_sdk_native_root=\"$OHOS_SDK\" \
    is_clang=true rtc_use_h264=true ffmpeg_branding=\"Chrome\""

    gn gen out/webrtc --args="$arguments"
    if [ $? -ne 0 ]
    then
        echo "[ERROR] webrtc config faield!"
        return 1
    fi
    
    ninja -C out/webrtc -v -j8 > build.log
    if [ $? -ne 0 ]
    then
        echo "[ERROR] webrtc build faield!"
        cat build.log
        return 1
    fi

    cd $OLDPWD

    return 0
}

function start_compile() {
    check_prepare
    if [ $? -ne 0 ]
    then
        echo "check prepare failed!"
        return 1
    fi
    
    start_build
    if [ $? -ne 0 ]
    then
        echo "build WEBRTC failed! ######################"
        return 1
    fi

    echo "build WEBRTC SUCCESS!! ####################"
    return 0
}

start_compile $@

exit $?

#eof
